<?php

namespace App\Services;

use App\Models\Crm_Care;
use App\Models\Crm_Dynamic;
use App\Models\Crm_Gift_Record;
use App\Models\Crm_Line_Apply;
use App\Models\Crm_Meet;
use App\Models\Crm_Member;
use App\Models\Crm_Member_Account;
use App\Models\Crm_Member_Allot;
use App\Models\Crm_Member_Annex;
use App\Models\Crm_Member_Auth;
use App\Models\Crm_Member_Cond;
use App\Models\Crm_Member_Delete;
use App\Models\Crm_Member_Follow;
use App\Models\Crm_Member_Follow_Annex;
use App\Models\Crm_Member_Match;
use App\Models\Crm_Member_Photo;
use App\Models\Crm_Member_Rotate;
use App\Models\Crm_Order;
use App\Models\Crm_Slip;
use App\Models\Crm_User;
use App\Models\Crm_User_Head;
use App\Models\Crm_Visit;
use App\Traits\External;
use App\Traits\ResponseApi;
use Carbon\Carbon;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Throwable;

class MemberService
{
    public function getList($params)
    {
        $field = config('fields.listFields');
        $result = Crm_Member::getFilter($params)->select($field)
            ->Nodrop()
            ->Nodel()
            ->paginate($params['pageSize']);
        $list['total'] = $result->total();
        $data = $result->toArray();
        $item = External::optionItem($data['data']);
        $list['list'] = $item;

        return $list;
    }

    public function getHeadList($params)
    {
        $result = Crm_User_Head::getFilter($params)->first();
        return json_decode($result->params,true);
    }

    public function memberHeadUpdate($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_User_Head::getFilter($params)->first();
            $res->params = $params['params'];
            if(!$res->save()){
                throw new \Exception("更新客户列表表头失败" );
            }

            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function memberAllot($params)
    {
        $ids = explode(',',$params['ids']);

        try {
            // 开始数据库事务
            DB::beginTransaction();

            $newuser = Crm_User::find($params['userid']);

            foreach ($ids as $id) {
                $res = Crm_Member::find($id);
                if(!empty($res->belongid)){
                    $olduser = Crm_User::find($res->belongid);
                    $olduserid = $res->belongid;
                    $oldusername = $olduser->username;
                }else{
                    $olduserid = null;
                    $oldusername = null;
                }

                $res->belongid = $params['userid'];
                //后期完善后台配置时，坠海时间再重新获取
                $res->droptime = Carbon::parse($res->droptime)->addDay(15)->toDateString();
                if(!$res->save()){
                    throw new \Exception("更新Crm_Member归属人失败 $id");
                }

                $ret = Crm_Member_Allot::create([
                    'agencyid' => $params['aid'],
                    'mid' => $id,
                    'olduserid' => $olduserid,
                    'oldusername' => $oldusername,
                    'newuserid' => $params['userid'],
                    'newusername' => $newuser->username,
                    'optionid' => $params['uid'],
                    'optionname' => $params['uname']
                ]);

                if(!$ret){
                    throw new \Exception("创建Crm_Member_Allot分配记录失败 ID $id");
                }
            }

            DB::commit();
            return true;

        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function memberDel($params)
    {
        $ids = explode(',',$params['ids']);

        try {
            // 开始数据库事务
            DB::beginTransaction();

            foreach ($ids as $id) {
                $res = Crm_Member::where('id',$id)->update(['is_del' => 'Y']);
                if(!$res){
                    throw new \Exception("更新Crm_Member软删除失败 $id");
                }

                $ret = Crm_Member_Delete::create([
                    'agencyid' => $params['aid'],
                    'mid' => $id,
                    'optionid' => $params['uid'],
                    'optionname' => $params['uname']
                ]);

                if(!$ret){
                    throw new \Exception("创建Crm_Member_Del删除记录失败 ID $id");
                }
            }

            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function memberDrop($params)
    {
        $ids = explode(',',$params['ids']);

        try {
            // 开始数据库事务
            DB::beginTransaction();

            foreach ($ids as $id) {
                $res = Crm_Member::find($id);

                if(!empty($res->belongid)){
                    $olduser = Crm_User::find($res->belongid);
                    $olduserid = $res->belongid;
                    $oldusername = $olduser->username;
                }else{
                    $olduserid = null;
                    $oldusername = null;
                }

                $res->isdrop = 'Y';    //坠海状态
                $res->intotime = Carbon::now()->toDateTimeString();     //坠海时间
                $res->dropreason = $params['dropreason'];   //坠海原因
                $res->dropremark = $params['dropremark'];   //坠海备注
                $res->belongid = 0;     //清空归属人
                $res->droptime = NULL;  //清空距离坠海时间
                $res->allottime = NULL;  //清空分配时间

                if(!$res->save()){
                    throw new \Exception("更新Crm_Member坠海状态失败 $id");
                }
                $dropreason = External::getParams('dropreason');
                $rotate = Crm_Member_Rotate::where('mid' , $id)->where('agencyid' , $params['aid'])->where('islast','Y')->first();
                $rotate->islast = 'N';
                $rotate->save();
                $ret = Crm_Member_Rotate::create([
                    'agencyid' => $params['aid'],
                    'mid' => $id,
                    'explain' => '主动放弃，放弃原因：' . $dropreason[$params['dropreason']],
                    'remark' => $params['dropremark'],
                    'olduserid' => $olduserid,   //原归属人id
                    'oldusername' => $oldusername,  //原归属人名称
                    'islast' => 'Y',
                    'optionid' => $params['uid'],
                    'optionname' => $params['uname']
                ]);

                if(!$ret){
                    throw new \Exception("创建Crm_Member_Rotate流转记录失败 ID $id");
                }
            }

            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function memberInfo($params)
    {
        $field = config('fields.infoFields');
        $annexFields = config('fields.annexFields');
        $authFields = config('fields.authFields');
        $member = Crm_Member::select($field)->find($params['mid']);
        $annex = $member->hasOneMemberAnnex()->select($annexFields)->first();
        $auth = $member->hasOneMemberAuth()->select($authFields)->first();
        $result['memberInfo'] = $member;
        $result['memberAnnexInfo'] = $annex;
        $result['memberAuthInfo'] = $auth;
        return $result;
    }

    public function updateMemberGender($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Member::find($params['mid']);
            $res->gender = $params['gender'];

            if(!$res->save()){
                throw new \Exception("更新Crm_Member客户性别失败" );
            }
            DB::commit();

            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function updateMemberUsername($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Member::find($params['mid']);
            $res->username = $params['username'];

            if(!$res->save()){
                throw new \Exception("更新Crm_Member客户昵称失败" );
            }
            DB::commit();

            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function updateMemberWinxin($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Member::find($params['mid']);
            $res->weixin = $params['weixin'];

            if(!$res->save()){
                throw new \Exception("更新Crm_Member客户微信失败" );
            }
            DB::commit();

            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function updateMemberIsHidden($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Member::find($params['mid']);
            $res->ishidden = $params['ishidden'];

            if(!$res->save()){
                throw new \Exception("更新Crm_Member客户信息失败" );
            }
            DB::commit();

            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }


    public function updateMemberIntention($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Member::find($params['mid']);
            $res->intention = $params['intention'];

            if(!$res->save()){
                throw new \Exception("更新Crm_Member客户意向失败" );
            }
            DB::commit();

            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function updateMemberStatus($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Member::find($params['mid']);
            $res->status = $params['status'];

            if(!$res->save()){
                throw new \Exception("更新Crm_Member客户状态失败" );
            }
            DB::commit();

            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function updateMemberBelongId($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();

            $newuser = Crm_User::find($params['userid']);

            $res = Crm_Member::find($params['mid']);

            if(!empty($res->belongid)){
                $olduser = Crm_User::find($res->belongid);
                $olduserid = $res->belongid;
                $oldusername = $olduser->username;
            }else{
                $olduserid = null;
                $oldusername = null;
            }

            $res->belongid = $params['userid'];
            if(!$res->save()){
                throw new \Exception("更新Crm_Member归属人失败 ");
            }

            $ret = Crm_Member_Allot::create([
                'agencyid' => $params['aid'],
                'mid' => $params['mid'],
                'olduserid' => $olduserid,
                'oldusername' => $oldusername,
                'newuserid' => $params['userid'],
                'newusername' => $newuser->username,
                'optionid' => $params['uid'],
                'optionname' => $params['uname'],
                'remark' => $params['remark']
            ]);

            if(!$ret){
                throw new \Exception("创建Crm_Member_Allot分配记录失败 ID ");
            }

            DB::commit();
            return true;

        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function updateMemberServiceId($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Member::find($params['mid']);
            $res->serviceid = $params['userid'];

            if(!$res->save()){
                throw new \Exception("更新Crm_Member客户服务人id失败" );
            }
            DB::commit();

            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function updateMember($params)
    {
        $fieldArr = $this->fieldFilter($params);
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $resBase = Crm_Member::where('id' ,$params['mid'])->update($fieldArr['base']);
            if(!$resBase){
                throw new \Exception("更新Crm_Member客户信息失败" );
            }
            $resAnnex = Crm_Member_Annex::where('mid' ,$params['mid'])->update($fieldArr['annex']);
            if(!$resAnnex){
                throw new \Exception("更新Crm_Member_Annex客户附属信息失败" );
            }
            $resAuth = Crm_Member_Auth::where('mid' ,$params['mid'])->update($fieldArr['auth']);
            if(!$resAuth){
                throw new \Exception("更新Crm_Member_Auth客户认证信息失败" );
            }
            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public static function fieldFilter($params)
    {
        if(isset($params['birthday'])){
            $ageArr = External::getAge($params['birthday'],Carbon::now());
            $age = $ageArr['total_age']['year'];
            $zodiac = External::zodiac($params['birthday']);
            $zodiacParams = External::getParams('zodiac');
            $zodiackey = array_search($zodiac, $zodiacParams);
            $constellation = External::constellation($params['birthday']);
            $constellationParams = External::getParams('constellation');
            $constellationkey = array_search($constellation, $constellationParams);
        }else{
            $age = null;
            $zodiackey = null;
            $constellationkey = null;
        }

        $base = [
            'birthday' => $params['birthday'] ?? null,
            'age' => $age,
            'zodiac' => $zodiackey,
            'constellation' => $constellationkey,
            'height' => $params['height'] ?: null,
            'weight' => $params['weight'] ?: null,
            'marry' => $params['marry'] ?: null,
            'education' => $params['education'] ?: null,
            'blood' => $params['blood'] ?: null,
            'school' => $params['school'] ?: null,
            'job' => $params['job'] ?: null,
            'salary' => $params['salary'] ?: null,
            'companytype' => $params['companytype'] ?: null,
            'province' => $params['province'] ?: null,
            'province_name' => $params['province_name'] ?: null,
            'city' => $params['city'] ?: null,
            'city_name' => $params['city_name'] ?: null,
            'area' => $params['area'] ?: null,
            'area_name' => $params['area_name'] ?: null,
            'reside_province' => $params['reside_province'] ?: null,
            'reside_province_name' => $params['reside_province_name'] ?: null,
            'reside_city' => $params['reside_city'] ?: null,
            'reside_city_name' => $params['reside_city_name'] ?: null,
            'reside_area' => $params['reside_area'] ?: null,
            'reside_area_name' => $params['reside_area_name'] ?: null,
            'house' => $params['house'] ?: null,
            'car' => $params['car'] ?: null,
            'smoking' => $params['smoking'] ?: null,
            'drinking' => $params['drinking'] ?: null,
            'national' => $params['national'] ?: null,
            'child' => $params['child'] ?: null,
            'interest'=> $params['interest'] ?: null,
            'personality'=> $params['personality'] ?: null,
            'remark'=>$params['remark'] ?: null,
            'intro'=>$params['intro'] ?: null,
            'evaluate'=>$params['evaluate'] ?: null
        ];

        $annex = [
            'qq' => $params['qq'] ?: null,
            'email' => $params['email'] ?: null,
            'tel' => $params['tel'] ?: null,
            'faith' => $params['faith'] ?: null,
            'sin' => $params['sin'] ?: null,
            'debt' => $params['debt'] ?: null,
            'familyback' => $params['familyback'] ?: null,
            'parentstatus' => $params['parentstatus'] ?: null,
            'parenteconomic' => $params['parenteconomic'] ?: null,
            'sibling' => $params['sibling'] ?: null,
            'allopatry'=> $params['allopatry'] ?: null,
            'wedtime'=> $params['wedtime'] ?: null,
            'wantchild'=>$params['wantchild'] ?: null,
            'focus'=>$params['focus'] ?: null,
            'liveparent'=>$params['liveparent'] ?: null
        ];

        $auth = [
            'idcard' => $params['idcard'] ?: null,
        ];

        return ['base' => $base,'annex' => $annex,'auth' => $auth];
    }

    public function updateMemberIntroStatus($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Member_Auth::where('mid' , $params['mid'])->first();
            $res->iflag = $params['iflag'];

            if(!$res->save()){
                throw new \Exception("更新Crm_Member_Auth客户自我介绍状态失败" );
            }
            DB::commit();

            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function saveMemberFollow($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Member_Follow::create([
                'mid' => $params['mid'],
                'agencyid' => $params['aid'],
                'mode' => $params['mode'],
                'intention' => $params['intention'],
                'content' => $params['content'],
                'nexttime' => $params['nexttime'],
                'imgs' => $params['imgs'],
                'optionid' => $params['uid'],
                'optionname' => $params['uname']
            ]);

            if(!$res){
                throw new \Exception("保存Crm_Member_Follow跟进记录失败" );
            }
            DB::commit();

            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }
    public function memberFollowDel($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Member_Follow::find($params['id']);
            $res->is_del = 'Y';
            if(!$res->save()){
                throw new \Exception("删除Crm_Member_Follow跟进记录失败" );
            }
            DB::commit();

            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }


    public function saveMemberFollowAnnex($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Member_Follow_Annex::create([
                'fid' => $params['id'],
                'content' => $params['content'],
                'optionid' => $params['uid'],
                'optionname' => $params['uname']
            ]);

            if(!$res){
                throw new \Exception("保存Crm_Member_Follow_Annex跟进记录批注失败");
            }
            DB::commit();

            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function memberFollowAnnexDel($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Member_Follow_Annex::find($params['id']);
            $res->is_del = 'Y';
            if(!$res->save()){
                throw new \Exception("删除Crm_Member_Follow_Annex跟进记录批注失败");
            }
            DB::commit();

            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function getMemberCond($params)
    {
        $cond = Crm_Member_Cond::where('mid',$params['mid'])->first();
        $cond->marry = json_decode($cond->marry,true);
        $cond->education = json_decode($cond->education,true);
        $cond->salary = json_decode($cond->salary,true);
        $cond->house = json_decode($cond->house,true);
        $cond->car = json_decode($cond->car,true);
        $cond->child = json_decode($cond->child,true);
        $cond->zodiac = json_decode($cond->zodiac,true);
        $cond->constellation = json_decode($cond->constellation,true);
        //婚况
        $marryArr = External::getParams('marry');
        $marryText = [];
        if(!empty($cond->marry)){
            foreach ($cond->marry as $v)
            {
                array_push($marryText,$marryArr[$v]);
            }
            $cond->marryText = implode(',',$marryText);
        }else{
            $cond->marryText = '';
        }

        //学历
        $educationArr = External::getParams('education');
        $educationText = [];
        if(!empty($cond->education)){
            foreach ($cond->education as $v)
            {
                array_push($educationText,$educationArr[$v]);
            }
            $cond->educationText = implode(',',$educationText);
        }else{
            $cond->educationText = '';
        }

        //年收入
        $salaryArr = External::getParams('salary');
        $salaryText = [];
        if(!empty($cond->salary)){
            foreach ($cond->salary as $v)
            {
                array_push($salaryText,$salaryArr[$v]);
            }
            $cond->salaryText = implode(',',$salaryText);
        }else{
            $cond->salaryText = '';
        }

        //房产
        $houseArr = External::getParams('house');
        $houseText = [];
        if(!empty($cond->house)){
            foreach ($cond->house as $v)
            {
                array_push($houseText,$houseArr[$v]);
            }
            $cond->houseText = implode(',',$houseText);
        }else{
            $cond->houseText = '';
        }

        //车子
        $carArr = External::getParams('car');
        $carText = [];
        if(!empty($cond->car)){
            foreach ($cond->car as $v)
            {
                array_push($carText,$carArr[$v]);
            }
            $cond->carText = implode(',',$carText);
        }else{
            $cond->carText = '';
        }

        //小孩
        $childArr = External::getParams('child');
        $childText = [];
        if(!empty($cond->child)){
            foreach ($cond->child as $v)
            {
                array_push($childText,$childArr[$v]);
            }
            $cond->childText = implode(',',$childText);
        }else{
            $cond->childText = '';
        }

        //生肖
        $zodiacArr = External::getParams('zodiac');
        $zodiacText = [];
        if(!empty($cond->zodiac)){
            foreach ($cond->zodiac as $v)
            {
                array_push($zodiacText,$zodiacArr[$v]);
            }
            $cond->zodiacText = implode(',',$zodiacText);
        }else{
            $cond->zodiacText = '';
        }

        //星座
        $constellationArr = External::getParams('constellation');
        $constellationText = [];
        if(!empty($cond->constellation)){
            foreach ($cond->constellation as $v)
            {
                array_push($constellationText,$constellationArr[$v]);
            }
            $cond->constellationText = implode(',',$constellationText);
        }else{
            $cond->constellationText = '';
        }

        return $cond;
    }

    public function memberCondUpdate($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Member_Cond::where('mid' , $params['mid'])->update($params);
            if(!$res){
                throw new \Exception("保存Crm_Member_Cond择偶条件失败");
            }

            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function getMemberPhoto($params)
    {
        return Crm_Member_Photo::where('mid',$params['mid'])
            ->select(['id','url','status'])
            ->Nodel()
            ->get();
    }

    public function memberPhotoInsert($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Member_Photo::create([
                'agencyid' => $params['aid'],
                'mid' => $params['mid'],
                'url' => $params['url'],
                'status' => 'pass'
            ]);
            if(!$res){
                throw new \Exception("添加Crm_Member_Photo相册状态失败");
            }

            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }
    public function memberPhotoStatusUpdate($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Member_Photo::find($params['id']);
            $res->status = $params['status'];
            if(!$res->save()){
                throw new \Exception("更新Crm_Member_Photo相册状态失败");
            }

            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function memberPhotoDel($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Member_Photo::find($params['id']);
            $res->is_del = 'Y';
            if(!$res->save()){
                throw new \Exception("删除Crm_Member_Photo相册失败");
            }

            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function memberInteractList($params)
    {
        if ($params['mode'] == 1 && $params['type'] == 1) {
            //线上社交信息->浏览与关注->浏览谁
            return $this->toVist($params);

        }
        if ($params['mode'] == 1 && $params['type'] == 2) {
            //线上社交信息->浏览与关注->被浏览
            $list = $this->beVist($params);
        }
        if ($params['mode'] == 1 && $params['type'] == 3) {
            //线上社交信息->浏览与关注->关注谁
            $list = $this->toCare($params);
        }
        if ($params['mode'] == 1 && $params['type'] == 4) {
            //线上社交信息->浏览与关注->被关注
            $list = $this->beCare($params);
        }
        if ($params['mode'] == 2) {
            //线上社交信息->小纸条（只查询该用户发送的小纸条）
            $list = $this->toSlip($params);
        }
        if ($params['mode'] == 3) {
            //线上社交信息->广场动态->该用户动态
            $list = $this->toDynamic($params);
        }
        if ($params['mode'] == 4 && $params['type'] == 1) {
            //线上社交信息->礼物->该赠送
            $list = $this->toGift($params);
        }
        if ($params['mode'] == 4 && $params['type'] == 2) {
            //线上社交信息->礼物->该被赠送
            $list = $this->beGift($params);
        }

        return $list;
    }

    public static function toVist($params)
    {
        // 查询条件为mid = $params['mid'],显示otherMember信息
        $result = Crm_Visit::getFilter($params)
            ->select(['id','mid','otherid','viewnums','created_at'])
            ->Nodel()
            ->paginate($params['pageSize']);
        $list['total'] = $result->total();

        $result = External::optionResult($result,2);
        $list['list'] = $result;
        return $list;
    }

    public static function beVist($params)
    {
        // 查询条件为otherid = $params['mid'],显示member信息
        $params['otherid'] = $params['mid'];
        unset($params['mid']);
        $result = Crm_Visit::getFilter($params)
            ->select(['id','mid','otherid','viewnums','created_at'])
            ->Nodel()
            ->paginate($params['pageSize']);
        $list['total'] = $result->total();
        $result = External::optionResult($result,1);
        $list['list'] = $result;
        return $list;
    }

    public static function toCare($params)
    {
        // 查询条件为mid = $params['mid'],显示otherMember信息
        $result = Crm_Care::getFilter($params)
            ->select(['id','mid','otherid','ismutual','created_at'])
            ->Nodel()
            ->paginate($params['pageSize']);
        $list['total'] = $result->total();
        $result = External::optionResult($result,2);
        $list['list'] = $result;

        return $list;
    }

    public static function beCare($params)
    {
        // 查询条件为otherid = $params['mid'],显示member信息
        $params['otherid'] = $params['mid'];
        unset($params['mid']);
        $result = Crm_Care::getFilter($params)
            ->select(['id','mid','otherid','ismutual','created_at'])
            ->Nodel()
            ->paginate($params['pageSize']);
        $list['total'] = $result->total();
        $result = External::optionResult($result,1);
        $list['list'] = $result;
        return $list;
    }

    public static function toSlip($params)
    {
        $result = Crm_Slip::getFilter($params)
            ->select(['id','mid','otherid','content','status','created_at'])
            ->paginate($params['pageSize']);
        $list['total'] = $result->total();
        $result = External::optionResult($result,2);
        $list['list'] = $result;

        return $list;
    }

    public static function toDynamic($params)
    {
        $result = Crm_Dynamic::getFilter($params)
            ->select(['id','mid','content','status','created_at'])
            ->paginate($params['pageSize']);
        $list['total'] = $result->total();
        foreach ($result as $key => $value){
            $result[$key]['imgs'] = $value->hasManyDynamicImg()->pluck('img');
            $commit = $value->hasManyDynamicComment()->StatusPass()->Nodel()->get();
            $commit = External::optionResult($commit,1);
            $result[$key]['comment'] = $commit;
        }
        $list['list'] = $result->items();
        return $list;
    }

    public static function toGift($params)
    {
        $result = Crm_Gift_Record::getFilter($params)
            ->select(['id','mid','otherid','giftid','created_at'])
            ->Nodel()
            ->paginate($params['pageSize']);
        $result->data = $result->makeHidden(['hasOneGift']);
        $list['total'] = $result->total();
        $result = External::optionResult($result,2);
        $list['list'] = $result;

        return $list;
    }

    public static function beGift($params)
    {
        // 查询条件为otherid = $params['mid'],显示member信息
        $params['otherid'] = $params['mid'];
        unset($params['mid']);
        $result = Crm_Gift_Record::getFilter($params)
            ->select(['id','mid','otherid','giftid','created_at'])
            ->Nodel()
            ->paginate($params['pageSize']);
        $result->data = $result->makeHidden(['hasOneGift']);
        $list['total'] = $result->total();
        $result = External::optionResult($result,1);
        $list['list'] = $result;

        return $list;
    }
    public function memberMate($params)
    {
        $list = [];
        //   若客户性别未知，直接返回空集合
        if ($params['gender'] == 3){
            $list['list'] = [];
            $list['total'] = 0;
            return $list;
        }

        //  构建匹配查询构造器
        $query = Crm_Member::query();
        if ($params['gender'] == 1){
            $conditionGender = 2;
        }
        if ($params['gender'] == 2){
            $conditionGender = 1;
        }
        //
        $showFields = config('fields.showFields');
        $query->select($showFields)->where('gender', $conditionGender)
            ->where('agencyid',$params['aid']);
        if(!empty($params['ishidden']))
            $query->where('ishidden',$params['ishidden']);
        if(!empty($params['maxage']))
            $query->where('age','<=',$params['maxage']);
        if(!empty($params['minage']))
            $query->where('age','>=',$params['maxage']);
        if(!empty($params['maxheight']))
            $query->where('height','<=',$params['maxheight']);
        if(!empty($params['minheight']))
            $query->where('height','>=',$params['minheight']);
        if(!empty($params['maxweight']))
            $query->where('weight','<=',$params['maxweight']);
        if(!empty($params['minweight']))
            $query->where('weight','>=',$params['minweight']);
//        var_dump(!empty(json_decode($params['marry'],true)));exit;
        if(!empty(json_decode($params['marry'],true))){
            $query->whereIn('marry',json_decode($params['marry'],true));
        }

        if(!empty(json_decode($params['education'],true))){
            $query->whereIn('education',json_decode($params['education'],true));
        }
        if(!empty(json_decode($params['salary'],true))){
            $query->whereIn('salary',json_decode($params['salary'],true));
        }
        if(!empty(json_decode($params['house'],true))){
            $query->whereIn('house',json_decode($params['house'],true));
        }
        if(!empty(json_decode($params['car'],true))){
            $query->whereIn('car',json_decode($params['car'],true));
        }
        if(!empty(json_decode($params['child'],true))){
            $query->whereIn('child',json_decode($params['child'],true));
        }
        if(!empty(json_decode($params['zodiac'],true))){
            $query->whereIn('zodiac',json_decode($params['zodiac'],true));
        }
        if(!empty(json_decode($params['constellation'],true))){
            $query->whereIn('constellation',json_decode($params['constellation'],true));
        }
        if(!empty($params['province'])){
            $query->where('province',$params['province']);
        }
        if(!empty($params['city'])){
            $query->where('city',$params['city']);
        }
        if(!empty($params['area'])){
            $query->where('area',$params['area']);
        }
        $membersWithScores = $query->get()->map(function ($member) use ($params) {
            $arr = [];

            //匹配度计算逻辑
            $score = 0;
            if(!empty($member->age)){
                $arr['age'] = $member->age;
                $score++;
            }

            if(!empty($member->height)){
                $arr['height'] = $member->height;
                $score++;
            }

            if(!empty($member->weight)){
                $arr['weight'] = $member->weight;
                $score++;
            }

            if(!empty($member->marry)){
                $arr['marry'] = $member->marry;
                $score++;
            }

            if(!empty($member->education)){
                $arr['education'] = $member->education;
                $score++;
            }

            if(!empty($member->salary)){
                $arr['salary'] = $member->salary;
                $score++;
            }

            if(!empty($member->house)){
                $arr['house'] = $member->house;
                $score++;
            }

            if(!empty($member->car)){
                $arr['car'] = $member->car;
                $score++;
            }

            if(!empty($member->child)){
                $arr['child'] = $member->child;
                $score++;
            }

            if(!empty($member->zodiac)){
                $arr['zodiac'] = $member->zodiac;
                $score++;
            }

            if(!empty($member->constellation)){
                $arr['constellation'] = $member->constellation;
                $score++;
            }

            if(!empty($member->province)){
                $arr['province'] = $member->province;
                $score++;
            }

            $member->score = $score;
            $member->percent = bcdiv($member->score,12,2) * 100;
            return $member;
        });
        // 根据分数排序
        $sortedMembers = $membersWithScores->sortByDesc('score')->values();

        $totalItems = $sortedMembers->count();
        $paginatedCustomers = new LengthAwarePaginator(
            $sortedMembers->forPage($params['page'], $params['pageSize'])->values(),
            $totalItems,
            $params['pageSize'],
            $params['page'],
        );
        $list['total'] = $paginatedCustomers->total();
        $data = $paginatedCustomers->toArray();
        $item = External::optionItem($data['data']);
        $list['list'] = $item;
        return $list;
    }

    public function memberMatchSave($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Member_Match::create([
                'agencyid' => $params['aid'],
                'mid' => $params['mid'],
                'otherid' => $params['otherid'],
                'option_id' => $params['uid'],
                'option_name' => $params['uname']
            ]);
            if(!$res->save()){
                throw new \Exception("添加Crm_Member_Match推荐失败");
            }
            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function memberSupperManage($params)
    {
        $account = Crm_Member_Account::where('agencyid',$params['aid'])
            ->where('mid',$params['mid'])
            ->first();
        $account->isfreeze = $account->hasOneMember->isfreeze;
        $account->istop = $account->hasOneMember->istop;
        $account->vipid = $account->hasOneMember->vipid;
        $account->vipstart = $account->hasOneMember->vipstart;
        $account->vipend = $account->hasOneMember->vipend;
        $account = $account->makeHidden(['hasOneMember']);
        return $account;
    }

    public function memberSupperManageSave($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $res = Crm_Member::find($params['mid']);
            $res->isfreeze = $params['isfreeze'];
            $res->istop = $params['istop'];
            $res->istop = $params['istop'];
            $res->istop = $params['istop'];
            if(!$res->save()){
                throw new \Exception("更新Crm_Member置顶、冻结状态失败");
            }

            DB::commit();
            return true;
        }catch (Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function memberServiceOrder($params)
    {
        if ($params['mode'] == 1 && $params['type'] == 1) {
            //服务订单->牵线申请->牵线谁
            return $this->toLine($params);

        }
        if ($params['mode'] == 1 && $params['type'] == 2) {
            //服务订单->牵线申请->被牵线
            $list = $this->beLine($params);
        }
        if ($params['mode'] == 2 && $params['type'] == 1) {
            //服务订单->约见工单->约见谁
            $list = $this->toMeet($params);
        }
        if ($params['mode'] == 2 && $params['type'] == 2) {
            //服务订单->约见工单->被约见
            $list = $this->beMeet($params);
        }

        if ($params['mode'] == 3) {
            //服务订单->订单记录
            $list = $this->getOrder($params);
        }
        if ($params['mode'] == 4) {
            //服务订单->推荐记录
            $list = $this->getMatch($params);
        }

        return $list;
    }

    public static function toLine($params)
    {
        // 查询条件为mid = $params['mid'],显示otherMember信息
        $result = Crm_Line_Apply::getFilter($params)->paginate($params['pageSize']);
        $list['total'] = $result->total();

        $result = External::optionResult($result,2);
        $list['list'] = $result;
        return $list;
    }
    public static function beLine($params)
    {
        // 查询条件为otherid = $params['mid'],显示member信息
        $params['otherid'] = $params['mid'];
        unset($params['mid']);
        $result = Crm_Line_Apply::getFilter($params)->paginate($params['pageSize']);
        $list['total'] = $result->total();
        $result = External::optionResult($result,1);
        $list['list'] = $result;
        return $list;
    }
    public static function toMeet($params)
    {
        // 查询条件为mid = $params['mid'],显示otherMember信息
        $result = Crm_Meet::getFilter($params)->paginate($params['pageSize']);
        $list['total'] = $result->total();

        $result = External::optionResult($result,2);
        $list['list'] = $result;
        return $list;
    }
    public static function beMeet($params)
    {
        // 查询条件为otherid = $params['mid'],显示member信息
        $params['otherid'] = $params['mid'];
        unset($params['mid']);
        $result = Crm_Meet::getFilter($params)->paginate($params['pageSize']);
        $list['total'] = $result->total();
        $result = External::optionResult($result,1);
        $list['list'] = $result;
        return $list;
    }
    public static function getOrder($params)
    {
        $result = Crm_Order::getFilter($params)->paginate($params['pageSize']);
        foreach ($result as &$value){
            $paymoney = $value->hasManyPayment()->sum('price');
            $refundmoney = $value->hasManyRefund()->sum('price');
            $value['paymoney'] = bcsub($paymoney,$refundmoney,2);
            $value['refundmoney'] = $refundmoney ?: '0.00';
            $value['contractStatus'] = $value->hasOneContract->status;
        }
        $result->data = $result->makeHidden(['hasOneContract']);
        // 取消引用
        unset($value);

        $list['total'] = $result->total();
        $list['list'] = $result->items();
        return $list;
    }
    public static function getMatch($params)
    {
        $result = Crm_Member_Match::getFilter($params)->paginate($params['pageSize']);
        $list['total'] = $result->total();
        $result = External::optionResult($result,3);
        $list['list'] = $result;
        return $list;
    }

    public function searchMember($params)
    {
        $field = config('fields.searchFields');
        return Crm_Member::getSearch($params)
            ->select($field)
            ->Nodel()
            ->get();
    }

    public function timesChecked($params)
    {
        if($params['type'] == 1) {
            $memberAccout = Crm_Member_Account::where('mid',$params['mid'])
                ->where('agencyid',$params['aid'])
                ->first();
            if(!empty($memberAccout) && $memberAccout->meettimes == 0){
                return ['status' => false, 'code' => 5007,'data' => []];
            }
        }

        if($params['type'] == 2) {
            $memberAccout = Crm_Member_Account::where('mid',$params['mid'])
                ->where('agencyid',$params['aid'])
                ->first();

            if(!empty($memberAccout) && $memberAccout->meettimes == 0){
                return ['status' => false, 'code' => 5007,'data' => []];
            }

            $otherMemberAccout = Crm_Member_Account::where('mid',$params['otherid'])
                ->where('agencyid',$params['aid'])
                ->first();
            if(!empty($otherMemberAccout) && $otherMemberAccout->meettimes == 0){
                return ['status' => false, 'code' => 5008,'data' => []];
            }
        }

        return ['status' => true, 'code' => 200,'data' => []];
    }
}
